<template>
  <section id="container"></section>
</template>
<script>
import { defineComponent, onMounted, reactive, toRefs } from "vue";
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
let scene, point;
export default defineComponent({
  setup() {
    const state = reactive({
      renderer: "",
      controls: "",
      camera: "",
      requestID: "",
    });
    // 加载场景
    const loadScene = () => {
      scene = new THREE.Scene();
    };
    // 加载相机
    const loadCamera = () => {
        state.camera=new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
        state.camera.position.set(200, 300, 200); //设置相机位置
        state.camera.lookAt(scene.position); //设置相机方向(指向的场景对象)
    };
    // 加载渲染器
    const loadRenderer = () => {
        state.renderer = new THREE.WebGLRenderer();
        state.renderer.setSize(window.innerWidth, window.innerHeight);
        let container = document.getElementById("container");
        state.renderer.setClearColor(0xb9d3ff, 1);
        container.appendChild(state.renderer.domElement);
        state.renderer.render(scene, state.camera);
    };
    // 加载控制器
    const loadController = () => {
        state.controls=new OrbitControls(state.camera,state.renderer.domElement);
        state.controls.addEventListener('change', render);
    };
    // 加载渲染实体
    const loadGeometry = () => {
      var geometry = new THREE.SphereGeometry(100, 25, 25); //创建一个球体几何对象
      var material = new THREE.PointsMaterial({
        color: 0x0000ff, //颜色
        size: 1, //点渲染尺寸
      });
      point=new THREE.Points(geometry,material)
      scene.add(point)
    };
    // 实际要执行的渲染
    const render = () => {
        point.rotation.x += 0.01;
        point.rotation.y += 0.01;
        state.renderer.render(scene, state.camera);
    };
    const animation = () => {
      state.requestID = requestAnimationFrame(animation);
      render();
    };
    const init = () => {
      loadScene();
      loadCamera();
      loadRenderer();
      loadController();
      loadGeometry();
      animation();
    };
    onMounted(() => {
      init();
    });
    return {
      ...toRefs(state),
    };
  },
});
</script>
